package ${package.ServiceImpl};


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${superServiceImplClassPackage};
import ${package.Mapper}.${table.mapperName};
import ${cfg.packageInfo}.dto.input.Select${entity}InputDTO;
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * ${table.comment!} 服务实现类
 *
 * @author ${author}
 * @date ${date}
 */
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName},${entity}>
        implements ${table.serviceName} {

    @Resource
    private ${table.mapperName} ${entity?uncap_first}Mapper;

    @Override
    public IPage<${entity}> select${entity}Page(Select${entity}InputDTO inputDTO) {

        Page<${entity}> page = new Page<>(inputDTO.getPageNum(), inputDTO.getPageSize());

        QueryWrapper<${entity}> queryWrapper = getQueryWrapper(inputDTO);

        return ${entity?uncap_first}Mapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<${entity}> select${entity}List(Select${entity}InputDTO inputDTO) {

        QueryWrapper<${entity}> queryWrapper = getQueryWrapper(inputDTO);

        return ${entity?uncap_first}Mapper.selectList(queryWrapper);
    }

    /**
     * 获取查询wrapper
     * @param inputDTO
     * @return
     */
     private static QueryWrapper<${entity}> getQueryWrapper(Select${entity}InputDTO inputDTO) {

        QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
        <#list table.fields as field>
            <#if field.propertyName == "createdAt" || field.propertyName == "updatedAt">
                <#else>
        if (!ObjectUtils.isEmpty(inputDTO.get${field.propertyName?cap_first}())){
                    <#if field.propertyType == "Integer">
            queryWrapper.eq("${field.name}", inputDTO.get${field.propertyName?cap_first}());
                    <#-- 字符串唯一值判断逻辑   -->
                    <#elseif field.propertyType == "String" && (field.name?contains("id") || field.comment?contains("唯一"))>
            queryWrapper.eq("${field.name}", inputDTO.get${field.propertyName?cap_first}());
                    <#elseif field.propertyType == "String">
            queryWrapper.like("${field.name}", inputDTO.get${field.propertyName?cap_first}());
                    </#if>
        }
           </#if>
        </#list>
        // 时间范围查询
        if (!ObjectUtils.isEmpty(inputDTO.getStartTime()) && !ObjectUtils.isEmpty(inputDTO.getEndTime())){
            queryWrapper.between("created_at", inputDTO.getStartTime(), inputDTO.getEndTime());
        }
        // 按照创建时间降序
        queryWrapper.orderByDesc("created_at");

        return queryWrapper;
     }


}
